<template>
  <div class="order-list">
    <h2>订单列表</h2>
    <el-button @click="goBackHome">返回首页</el-button>
    <el-button type="primary" @click="goToAddOrder">添加订单</el-button>

    <div class="search-form">
      <el-input v-model="searchParams.order_id" placeholder="订单ID" clearable style="width: 180px" />
      <el-input v-model="searchParams.order_name" placeholder="订单名称" clearable style="width: 200px" />
      <el-select
        v-model="searchParams.order_status"
        placeholder="订单状态"
        clearable
        style="width: 150px"
      >
        <el-option
          v-for="status in statusOptions"
          :key="status.value"
          :label="status.label"
          :value="status.value"
        />
      </el-select>
      <el-input v-model="searchParams.order_phone" placeholder="联系电话" clearable style="width: 180px" />
      <el-input v-model="searchParams.order_province" placeholder="省份" clearable style="width: 120px" />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <div class="filter-buttons">
      <el-button
        v-for="status in statusOptions.filter(s => s.value)"
        :key="status.value"
        :type="selectedStatus === status.value ? 'primary' : ''"
        @click="toggleStatusFilter(status.value)"
      >
        {{ status.label }}
      </el-button>
    </div>

    <div class="custom-table">
      <table>
        <thead>
          <tr>
            <th>订单ID</th>
            <th>订单名称</th>
            <th>订单价格</th>
            <th>订单状态</th>
            <th>联系电话</th>
            <th>收货地址</th>
            <th>省份</th>
            <th>商品列表</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in currentPageOrders" :key="order.order_id">
            <td>{{ order.order_id }}</td>
            <td>{{ order.order_name }}</td>
            <td>{{ order.order_price }}</td>
            <td>
              <el-tag :type="getStatusType(order.order_status)" effect="dark">
                {{ getStatusText(order.order_status) }}
              </el-tag>
            </td>
            <td>{{ order.order_phone }}</td>
            <td>{{ order.order_address }}</td>
            <td>{{ order.order_province }}</td>
            <td>
              <el-tag
                v-for="goods in order.bs_order_goods"
                :key="goods.id"
                style="margin-right: 5px"
              >
                {{ goods.goods_name }} (x{{ goods.goods_num }})
              </el-tag>
            </td>
            <td>
              <!-- 根据订单状态动态渲染按钮 -->
              <el-button
                v-if="order.order_status === 7 || order.order_status === 5"
                type="primary"
                size="small"
                @click="editOrder(order.order_id)"
              >
                支付
              </el-button>
              <el-button
                v-else
                type="primary"
                size="small"
                @click="editOrder(order.order_id)"
              >
                详情
              </el-button>
              <el-button v-if="order.order_status === 7 || order.order_status === 5" type="danger" size="small" @click="deleteOrder(order.order_id)">取消订单</el-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredOrders.length"
    >
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      searchParams: {
        order_id: '',
        order_name: '',
        order_status: null,
        order_phone: '',
        order_province: ''
      },
      orders: [],
      loading: true,
      statusOptions: [
        { value: null, label: '全部' },
        { value: 7, label: '未付款' },
        { value: 1, label: '支付待审核' },
        { value: 2, label: '待发货' },
        { value: 3, label: '已发货' },
        { value: 4, label: '已签收' },
        { value: 5, label: '审核未通过' },
        { value: 6, label: '已退货' }
      ],
      selectedStatus: null,
      currentPage: 1,
      pageSize: 10,
      orderAdmin: '' // 新增一个字段来存储路由参数
    };
  },
  created() {
    this.orderAdmin = this.$route.params.order_admin; // 获取路由参数
    this.fetchOrders();
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => {
        // 根据 orderAdmin 过滤订单
        const matchAdmin = this.orderAdmin === 'admin' ? true : order.order_admin === this.orderAdmin;

        const matchSearch = [
          String(order.order_id).includes(this.searchParams.order_id),
          order.order_name.includes(this.searchParams.order_name),
          order.order_phone.includes(this.searchParams.order_phone),
          order.order_province.includes(this.searchParams.order_province),
          this.searchParams.order_status ? order.order_status === this.searchParams.order_status : true
        ].every(Boolean);

        const matchStatus = this.selectedStatus ? order.order_status === this.selectedStatus : true;

        return matchAdmin && matchSearch && matchStatus;
      });
    },
    currentPageOrders() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredOrders.slice(start, end);
    }
  },
  methods: {
    fetchOrders() {
      this.loading = true;
      axios.get('http://127.0.0.1:3005/order/getOrders')
        .then(response => {
          if (response.data && response.data.res && response.data.res.result) {
            // 根据 orderAdmin 过滤订单
            if (this.orderAdmin !== 'admin') {
              this.orders = response.data.res.result.filter(order => order.order_admin === this.orderAdmin);
            } else {
              this.orders = response.data.res.result;
            }
          } else {
            this.$message.error('订单数据格式错误');
          }
          this.loading = false;
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单查询失败');
          this.loading = false;
        });
    },
    handleSearch() {
      this.selectedStatus = null;
      this.currentPage = 1;
      this.fetchOrder();
    },
    resetSearch() {
      this.searchParams = {
        order_id: '',
        order_name: '',
        order_status: null,
        order_phone: '',
        order_province: ''
      };
      this.selectedStatus = null;
      this.currentPage = 1;
      this.fetchOrder();
    },
    toggleStatusFilter(status) {
      this.selectedStatus = this.selectedStatus === status ? null : status;
      this.currentPage = 1;
    },
    fetchOrders() {
      axios.get('http://127.0.0.1:3005/order/getOrders')
        .then(response => {
          if (response.data && response.data.res && response.data.res.result) {
            this.orders = response.data.res.result;
          } else {
            this.$message.error('订单数据格式错误');
          }
          this.loading = false;
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单查询失败');
          this.loading = false;
        });
    },
    deleteOrder(id) {
      this.$confirm('确定删除此订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://127.0.0.1:3005/order/${id}`)
          .then(() => {
            this.$message.success('订单删除成功');
            this.fetchOrders();
          })
          .catch(error => {
            console.error(error);
            this.$message.error('订单删除失败');
          });
      });
    },
    editOrder(id) {
      this.$router.push(`/Order/Detail/${id}`);
    },
    goToAddOrder() {
      this.$router.push(`/Order/Add/${this.$route.params.order_admin}`);
    },
    goBackHome() {
      this.$router.push('/home');
    },
    getStatusText(status) {
      const statusMap = {
        7: '未付款',
        1: '支付待审核',
        2: '待发货',
        3: '已发货',
        4: '已签收',
        5: '审核未通过',
        6: '已退货'
      };
      return statusMap[status] || '未知状态';
    },
    getStatusType(status) {
      const typeMap = {
        1: 'warning',
        2: 'warning',
        3: 'primary',
        4: 'success',
        5: 'primary',
        6: 'info',
        7: 'danger'
      };

      return typeMap[status] || 'info';
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    }
  }
    // 其他方法保持不变
  
};
</script>

<style scoped>
.order-list {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

h2 {
  color: var(--el-text-color-primary);
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  align-items: center;
}

h2::before {
  content: "";
  width: 4px;
  height: 18px;
  background: var(--el-color-primary);
  margin-right: 12px;
  border-radius: 2px;
}

.search-form {
  margin: 20px 0;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  padding: 15px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
}

.filter-buttons {
  margin: 20px 0;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.custom-table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

.custom-table table {
  width: 100%;
  border-collapse: collapse;
}

.custom-table th,
.custom-table td {
  padding: 12px;
  border: 1px solid var(--el-border-color-light);
  text-align: left;
}

.custom-table th {
  background-color: var(--el-fill-color-light);
  font-weight: 600;
}

.custom-table tr:nth-child(even) {
  background-color: var(--el-fill-color-lighter);
}

.custom-table tr:hover {
  background-color: var(--el-fill-color-light);
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }

  .filter-buttons {
    justify-content: center;
  }

  .custom-table {
    overflow-x: auto;
  }

  .custom-table th,
  .custom-table td {
    white-space: nowrap;
  }
}
</style>